<template>
  <div class="kpi-daily">
    <v-calendar ref="calendarRef" :attributes='dailyInfo.attrs'
                @dayclick="dateClick" @did-move="changeMonthClick"
                :is-dark="appStore.isDark"
                class="kpi-calendar card-item"/>

    <kpi-card v-if="dailyInfo.dailyKpiList.length !== 0"
        :item-list="dailyInfo.dailyKpiList"/>

    <el-empty v-else description="今日暂无绩效" />
  </div>
</template>

<script setup lang="ts">
import KpiCard from '@/components/kpi/KpiCard.vue'
import { reactive, watch, ref } from 'vue'
import { formatDate, getStartEndDate } from 'vue3-common/utils/dateUtil'
import { CalendarDay } from 'v-calendar/dist/types/src/utils/page'
import { useAppStore } from '@/store/app.ts'
import { useKpiStore } from '@/store/kpi.ts'
import { IKpi } from '@/types/kpi.ts'

const calendarRef = ref()
const appStore = useAppStore()
const kpiStore = useKpiStore()

watch(() => kpiStore.isRefresh, () => {
  updateInfo()
})

const dailyInfo = reactive({
  calendarDate: '',
  dailyKpiList: [] as IKpi[],
  attrs: [] as any[]
})

const updateInfo = () => {
  getCalendarMoveDate()
  getCalendarAttrDates()
}

const getCalendarMoveDate = () => {
  const recordLength = kpiStore.kpiList.length
  if (recordLength > 0) {
    dailyInfo.dailyKpiList = getKpiDay(formatDate(new Date()))
  }
}

const getCalendarAttrDates = () => {
  dailyInfo.attrs = []
  dailyInfo.attrs.push({
    key: 'today',
    highlight: true,
    dates: new Date()
  })

  const dateList = kpiStore.kpiList.map((item) => item.date)
  dailyInfo.attrs.push({
    dot: 'red',
    dates: [...new Set(dateList)]
  })
}

/**
 * 选择日期事件
 * @param day 日期
 */
const dateClick = (day: CalendarDay) => {
  dailyInfo.dailyKpiList = getKpiDay(formatDate(day.date))
}

const getKpiDay = (date: string): IKpi[] => {
  return kpiStore.kpiList.filter((item) => formatDate(item.date) === date)
}

/**
 * 选择月份事件
 */
const changeMonthClick = async (value) => {
  const month = value[0].id
  dailyInfo.dailyKpiList = []
  kpiStore.queryInfo.startDate = getStartEndDate(month, 'month')[0]
  kpiStore.queryInfo.endDate = getStartEndDate(month, 'month')[1]
  await kpiStore.refreshInfo()
}
</script>

<style lang="scss">
.kpi-daily {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1vh;

  .kpi-calendar {
    width: 100%;
  }
}
</style>
